<template>
  <a-card>
    <TableSearch
      ref="tableSearch"
      :fields="fields"
      @searchEmit="searchEmit"
      @resetEmit="resetEmit"
      :isRefreshBtn="true"
      @refreshEmit="$refs.table.refresh()"
      :toolSettings="toolSettings"
    />
    <s-table
      ref="table"
      rowKey="id"
      :size="tableSize"
      :columns="columns"
      :data="tableData"
      :scroll="{ x: 1000 }"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, fixed: true }"
    >
      <template slot="realname" slot-scope="text, record">
        <span >{{ text || record.nickname }}</span>
      </template>
      <template slot="status" slot-scope="text">
        <a-tag v-if="text == 0" class="cursor">未支付</a-tag>
        <a-tag v-if="text == 1" class="cursor" color="#52c41a">已支付</a-tag>
      </template>
      <template slot="orderCode" slot-scope="text">
        <span style="font-weight: bold;">{{ text }}</span>
        <a-button @click="copy(text)" v-if="text" type="link" size="small">复制</a-button>
      </template>
      <template slot="payType" slot-scope="text">
        <span >{{ payTypeFormat(text) }}</span>
      </template>
      <template slot="pay" slot-scope="text, record">
        <span v-if="text">{{ text }}<span v-if="record.status == 0">&nbsp;(预付)</span></span>
      </template>
      <template slot="o" slot-scope="text, record">
        <a-button @click="edit(record)" type="link" size="small">编辑</a-button>
      </template>
    </s-table>
    <Imitate ref="Imitate" :payTypeOptions="payTypeOptions" :placeOptions="placeOptions" />
    <RecordForm ref="RecordForm" :payTypeOptions="payTypeOptions" :placeOptions="placeOptions" />
  </a-card>
</template>

<script>
import { TableSearch, STable } from '@/components'
import { addRecordAPI, getRecordListAPI, editRecordAPI } from '@/api/record.js'
import { getPayTypeAPI } from '@/api/dictionary.js'
import { getEasyPlaceListAPI } from '@/api/place.js'
import { searchEmit, resetEmit } from '@/views/biz/common'
import Imitate from './modules/Imitate.vue'
import RecordForm from './modules/RecordForm.vue'
import { downloadFile } from '@/utils/util'

export default {
  components: { TableSearch, STable, Imitate, RecordForm },
  data () {
    return {
      payTypeOptions: [],
      placeOptions: [],
      toolSettings: [
        { text: '模拟车辆进出记录', icon: 'play-square', type: '#5a89ff', click: () => { this.imitate() } },
        { text: '导出', icon: 'export', type: 'primary', click: this.export, loading: false }
      ],
      fields: [
        { field: 'number', type: 'input', label: '车牌号码', value: '', placeholder: '请输入' },
        { field: 'realname', type: 'input', label: '用户姓名', value: '', placeholder: '请输入' },
        { field: 'phone', type: 'input', label: '联系电话', value: '', placeholder: '请输入' },
        { field: 'status', type: 'select', label: '支付状态', value: undefined, placeholder: '请选择', options: [{ label: '未支付', value: 0 }, { label: '已支付', value: 1 }] },
        { field: 'orderCode', type: 'input', label: '订单号', value: '', placeholder: '请输入' },
        { field: 'payType', type: 'select', label: '支付方式', value: undefined, placeholder: '请选择', options: [] },
        { field: 'placeId', type: 'select', label: '车位编号', value: undefined, placeholder: '请选择', options: [] }
      ],
      columns: [
        { title: '车牌号码', dataIndex: 'number', width: 100, align: 'center' },
        { title: '用户姓名', dataIndex: 'realname', width: 100, scopedSlots: { customRender: 'realname' } },
        { title: '联系电话', dataIndex: 'phone', width: 120, align: 'center' },
        { title: '支付状态', dataIndex: 'status', width: 100, align: 'center', scopedSlots: { customRender: 'status' } },
        { title: '订单号', dataIndex: 'orderCode', width: 240, align: 'center', scopedSlots: { customRender: 'orderCode' } },
        { title: '停车费(元)', dataIndex: 'pay', width: 100, align: 'center', scopedSlots: { customRender: 'pay' } },
        { title: '停车时长', dataIndex: 'timeCount', width: 120, align: 'center' },
        { title: '支付方式', dataIndex: 'payType', width: 130, align: 'center', scopedSlots: { customRender: 'payType' } },
        { title: '停车开始时间', dataIndex: 'startTime', width: 150, align: 'center' },
        { title: '停车结束时间', dataIndex: 'endTime', width: 150, align: 'center' },
        { title: '车位编号', dataIndex: 'placeCode', width: 80, align: 'center' },
        { title: '备注', dataIndex: 'note', width: 200, ellipsis: true },
        { title: '更新时间', dataIndex: 'updateTime', width: 150, align: 'center' },
        { title: '操作', dataIndex: 'operation', align: 'center', width: 100, scopedSlots: { customRender: 'o' }, fixed: 'right' }
      ],
      tableData: query => {
        return getRecordListAPI(Object.assign(query, this.params))
      },
      params: {
        number: '',
        realname: '',
        phone: '',
        status: undefined,
        orderCode: '',
        payType: undefined,
        placeId: undefined
      },
      selectedRowKeys: []
    }
  },
  created () {
    this.getPayType()
    getEasyPlaceListAPI().then(res => {
      this.placeOptions = res.data.rows.map(item => {
        if (item.type === 0) {
          return {
            ...item,
            label: `${item.code}（自由车位）`,
            value: item.id
          }
        } else {
          return {
            ...item,
            label: `${item.code}（固定车位）`,
            value: item.id
          }
        }
      })
      const fieldItem = this.fields.find(item => item.field === 'placeId')
      fieldItem.options = this.placeOptions
    })
  },
  methods: {
    searchEmit,
    resetEmit,
    /** @name 模拟车辆进出记录 **/
    imitate () {
      this.$refs.Imitate.open('模拟车辆进出记录', null, (form, done) => {
        addRecordAPI(form).then(() => {
          this.$refs.table.refresh(true)
          this.$message.success({
            content: h => <span>成功模拟了一台车<span style={{ color: form.status === 0 ? '#ff4d4f' : '#52c41a' }}>{form.status === 0 ? '入库' : '出库'}</span></span>
          })
          done(true)
        }).finally(() => {
          done(false)
        })
      })
    },
    /** @name 复制 **/
    copy (text) {
      const textarea = document.createElement('textarea')
      textarea.setAttribute('readonly', 'readonly')
      textarea.value = text
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      this.$message.success('复制成功')
    },
    /** @name 获取支付方式 **/
    getPayType () {
      getPayTypeAPI().then(res => {
        this.payTypeOptions = res.data.rows
        const fieldItem = this.fields.find(item => item.field === 'payType')
        fieldItem.options = this.payTypeOptions
      })
    },
    payTypeFormat (value) {
      return this.payTypeOptions.find(item => item.value === value)?.label || '-'
    },
    /** @name 编辑进出记录 **/
    edit (record) {
      this.$refs.RecordForm.open('编辑进出记录', this.deepClone(record), (form, done) => {
        editRecordAPI({
          ...form,
          id: record.id
        }).then(() => {
          this.$refs.table.refresh()
          this.$message.success('编辑成功')
          done(true)
        }).finally(() => {
          done(false)
        })
      })
    },
    /** @name 勾选 **/
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
      console.log(this.selectedRowKeys)
    },
    /** @name 导出 **/
    export () {
      if (this.selectedRowKeys.length === 0) {
        return this.$message.error('请选择导出数据')
      }
      const target = this.toolSettings.find(item => item.text === '导出')
      target.loading = true
      downloadFile('/record/import', { ids: this.selectedRowKeys.join(',') }).then(() => {
        this.$message.success('导出成功')
      }).finally(() => {
        target.loading = false
      })
    }
  }
}
</script>
